//
// File:	GameRuleManager.cpp
// Author:	Thomas TISSOT-DUPONT
// Login:	<thomas.tissotdupont@free.fr>
//
// Created:	23/04/2010 at 23:00:00
// Purpose:	
//
#include "Base.hpp"
#include "GameRuleManager.hpp"
#include "Trace.hpp"

//------------------------------------------------------------------
// Constructor / Destructor
//------------------------------------------------------------------
GameRuleManager::GameRuleManager()
	:	m_gameruleFactories(),
		m_pCurrentGameRule(NULL)
{
}

GameRuleManager::~GameRuleManager()
{
	StopGameRule();
}

//------------------------------------------------------------------
// Install GameRule
//------------------------------------------------------------------
void GameRuleManager::InstallGameRule(const std::string &name, pfnGameRuleFactory factory)
{
	//What if we have two gamerules using the same name ?
	if (factory != NULL)
	{
		m_gameruleFactories[name] = factory;
		Trace::debug << "GameRuleManager::InstallGameRule: " << name << std::endl;
	}
}

//------------------------------------------------------------------
// Has GameRule ?
//------------------------------------------------------------------
bool GameRuleManager::HasGameRule(const std::string &name) const
{
	if (m_gameruleFactories.find(name) == m_gameruleFactories.end())
		return false;
	return true;
}

//------------------------------------------------------------------
// Start / Stop GameRule
//------------------------------------------------------------------
bool GameRuleManager::StartGameRule(const std::string &name)
{
	if (m_gameruleFactories.find(name) == m_gameruleFactories.end() && m_gameruleFactories[name] != NULL)
	{
		Trace::debug << "Cannot find gamerule: " << name << std::endl;
		return false;
	}
	StopGameRule();
	m_pCurrentGameRule = (*m_gameruleFactories[name])();
	return m_pCurrentGameRule->OnStart();
}

void GameRuleManager::StopGameRule()
{
	if (m_pCurrentGameRule != NULL)
	{
		m_pCurrentGameRule->OnStop();
		delete m_pCurrentGameRule;
		m_pCurrentGameRule = NULL;
	}
}

//------------------------------------------------------------------
// Current GameRule
//------------------------------------------------------------------
IGameRule *GameRuleManager::GetCurrentGameRule() const
{
	return m_pCurrentGameRule;
}

//------------------------------------------------------------------
// Update
//------------------------------------------------------------------
void GameRuleManager::Update()
{
	if (m_pCurrentGameRule != NULL)
	{
		m_pCurrentGameRule->Update();
	}
}
